let bills = [];
let currentPage = 1;
const billsPerPage = 10;
const billsJsonUrl = 'http://localhost:5500/bill2/bills/bills.json'; 

//添加账单函数
function addBill() {
  const date = document.getElementById('date').value;
  const source = document.getElementById('source').value;
  const amountInput = document.getElementById('amount').value;
  const amount = parseFloat(amountInput);
  console.log('========================================');
  console.log('开始添加账单...');
  console.log('日期:', date);
  console.log('来源:', source);
  console.log('原始金额输入:', amountInput);
  console.log('解析后的金额:', amount);

  if (isNaN(amount)) {
    console.error('金额输入无效');
    alert('请输入有效的金额');
    return;
  }

  const bill = {
    date,
    source,
    amount,
    type: amount > 0 ? 'income' : 'expense',
    originalAmount: amountInput
  };

  console.log('新添加的账单:', bill);

  bills.unshift(bill);
  console.log('账单数组更新后:', bills);
  renderBills(currentPage, true);
  calculateTotal();
  clearForm();
  updatePaginationControls();
  
  console.log('账单添加完成');
  console.log('========================================');
}

//渲染账单页面
function renderBills(page, insertAtTop = false) {
  const billItems = document.getElementById('bill-items');
  billItems.innerHTML = '';

  const start = (page - 1) * billsPerPage;
  const end = Math.min(start + billsPerPage, bills.length);
  const pageBills = bills.slice(start, end);
  console.log('========================================');
  console.log('开始渲染账单页面:', page);
  console.log('要渲染的账单数量:', pageBills.length);

  pageBills.forEach((bill, index) => {
    const li = document.createElement('li');
    li.innerHTML = `
      <span>${bill.date}</span>
      <span>${bill.source}</span>
      <span style="color: ${bill.type === 'expense' ? 'red' : 'green'}">${bill.amount.toFixed(2)}</span>
      <button onclick="deleteBill(${index + start})">删除</button>
    `;
    billItems.appendChild(li);
  });

  console.log('账单页面渲染完成');
  console.log('========================================');
}

//上传账单函数
function uploadBills() {
  const fileUpload = document.getElementById('file-upload');
  console.log('========================================');
  console.log('开始处理上传的文件...');
  if (fileUpload.files.length === 0) {

    console.log('没有选择文件');
    alert('请选择要上传的JSON文件');

    return;
  }

  const file = fileUpload.files[0];
  const reader = new FileReader();

  reader.onload = function(event) {
    try {
      const jsonData = JSON.parse(event.target.result);
      if (!Array.isArray(jsonData)) {
        throw new Error('上传的文件内容不是一个数组');
      }

      console.log('开始处理上传的账单数据...');
      console.log('上传的账单数据:', jsonData);

      // 更新账单数组，并正确处理支出和收入的金额
      bills = jsonData.map(bill => ({
        ...bill,
        amount: parseFloat(bill.amount), 
        type: bill.amount > 0 ? 'income' : 'expense'
      }));

      console.log('更新后的账单数组:', bills);

      renderBills(currentPage);
      calculateTotal();
      updatePaginationControls();
      clearForm();
      console.log('账单上传并处理完成');
    } catch (error) {
      console.error('处理上传文件时出错:', error.message);
      alert('上传的文件格式不正确: ' + error.message);
    }
  
  };

  reader.readAsText(file);
  console.log('开始读取文件...');
  console.log('========================================');
}

//计算总金额
function calculateTotal() {
  let total = 0;
  console.log('========================================');
  console.log('开始计算总金额...');

  bills.forEach(bill => {
    if (bill.type === 'income') {
      total += bill.amount;
    } else if (bill.type === 'expense') {
      total -= Math.abs(bill.amount);
    }
  });

  console.log('计算后的总金额:', total);
  document.getElementById('total-amount').innerText = `总金额: ${total.toFixed(2)}元`;
  console.log('总金额已更新到DOM');
  console.log('========================================');
}

//清除表单
function clearForm() {
  document.getElementById('date').value = '';
  document.getElementById('source').value = '';
  document.getElementById('amount').value = '';
}

//删除账单
function deleteBill(index) {
  bills.splice(index, 1);
  renderBills(currentPage);
  calculateTotal();
  updatePaginationControls();
}

//更新分页控件
function updatePaginationControls() {
  const totalPages = Math.ceil(bills.length / billsPerPage);
  const prevPageButton = document.getElementById('prev-page');
  const nextPageButton = document.getElementById('next-page');
  const pageInfo = document.getElementById('page-info');

  prevPageButton.disabled = currentPage === 1;
  nextPageButton.disabled = currentPage === totalPages;
  pageInfo.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
}

// 更新账单图表
function updateChart() {
  try {
    const ctx = document.getElementById('billChart').getContext('2d');
    if (!ctx) {
      throw new Error('Canvas element not found');
    }

    const labels = bills.map(bill => bill.date); 
    const incomeData = bills.filter(bill => bill.type === 'income').map(bill => bill.amount);
    const expenseData = bills.filter(bill => bill.type === 'expense').map(bill => bill.amount);

    new Chart(ctx, {
      type: 'bar', 
      data: {
        labels: labels,
        datasets: [
          {
            label: '收入',
            data: incomeData,
            backgroundColor: '#4caf50',
            borderColor: '#4caf50',
            borderWidth: 1
          },
          {
            label: '支出',
            data: expenseData,
            backgroundColor: '#f44336', 
            borderColor: '#f44336',
            borderWidth: 1
          }
        ]
      },
      options: {
        responsive: true,
        scales: {
          y: {
            beginAtZero: true
          },
          x: {
            stacked: true 
          }
        }
      }
    });
  } catch (error) {
  }
}

// 分页按钮点击事件
document.getElementById('prev-page').addEventListener('click', () => {
  if (currentPage > 1) {
    currentPage--;
    renderBills(currentPage);
    updatePaginationControls();
  }
});

document.getElementById('next-page').addEventListener('click', () => {
  const totalPages = Math.ceil(bills.length / billsPerPage);
  if (currentPage < totalPages) {
    currentPage++;
    renderBills(currentPage);
    updatePaginationControls();
  }
});

// 下载账单函数，支持JSON和CSV格式
function downloadBills(format = 'json') {
  let dataStr;
  let fileName;

  if (format === 'json') {
      dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(bills));
      fileName = "bills.json";
  } else if (format === 'csv') {
      // 添加列标题
      const csvHeader = ["日期", "来源", "金额", "类型", "原始金额"].join(",");
      // 生成账单数据的CSV行
      const csvContent = bills.map(bill => [
          bill.date,
          bill.source,
          bill.amount.toFixed(2),
          bill.type,
          bill.originalAmount
      ].join(",")).join("\n");
      // 合并列标题和账单数据
      dataStr = "data:text/csv;charset=utf-8," + encodeURIComponent(csvHeader + "\n" + csvContent);
      fileName = "bills.csv";
  } else {
      console.error('Unsupported format');
      return;
  }

  const downloadAnchorNode = document.createElement('a');
  downloadAnchorNode.setAttribute("href", dataStr);
  downloadAnchorNode.setAttribute("download", fileName);
  document.body.appendChild(downloadAnchorNode);
  downloadAnchorNode.click();
  downloadAnchorNode.remove();
}

//csv下载
document.getElementById('download-csv').addEventListener('click', () => {
  downloadBills('csv');
});

//清空账单
function clearBills() {
  bills = [];
  renderBills();
  calculateTotal();
  clearForm();
}

//主程序
window.onload = function() {
  // 尝试从本地存储加载账单
  const storedBills = JSON.parse(localStorage.getItem('bills')) || [];
  bills = storedBills;

  // 从指定的URL加载并解析JSON文件
  fetch(billsJsonUrl)
    .then(response => response.json())
    .then(data => {
      // 假设返回的JSON数据是一个数组，每个元素代表一个账单
      if (Array.isArray(data)) {
        // 更新账单数组
        bills = data.map(bill => ({
          ...bill,
          amount: parseFloat(bill.amount),
          type: bill.amount > 0 ? 'income' : 'expense'
        }));

        // 重新渲染账单页面
        renderBills(currentPage);
        calculateTotal();
        updatePaginationControls();
        updateChart();
      } else {
        console.error('加载的JSON数据格式不正确，不是一个数组');
      }
    })
    .catch(error => {
      console.error('加载JSON文件时出错:', error);
    });

  // 初始渲染账单页面
  renderBills(currentPage);
  calculateTotal();
  updatePaginationControls();
  updateChart();
};

// 侧栏窗口
document.addEventListener('DOMContentLoaded', function() {
  const sidebar = document.getElementById('sidebar');
  const toggleButton = document.getElementById('toggle-sidebar-button');

  toggleButton.addEventListener('click', function() {
    sidebar.classList.toggle('visible');
    toggleButton.textContent = sidebar.classList.contains('visible') ? '关闭说明' : '打开说明';
  });

  document.getElementById('close-sidebar').addEventListener('click', function() {
    sidebar.classList.remove('visible');
    toggleButton.textContent = '打开说明';
  });
});


window.addEventListener('click', function(event) {
  if (event.target && (event.target.matches('button[onclick*="addBill"]') || event.target.matches('button[onclick*="deleteBill"]'))) {
    localStorage.setItem('bills', JSON.stringify(bills));
    updateChart();
    console.log('账单已保存到本地存储:', bills);
    console.log('========================================');
  }
});

window.addEventListener('error', function(event) {
  console.log('========================================');
  console.error('发生错误:', event.message, event.filename, event.lineno, event.colno);
  console.log('========================================');
});



